<?php

/**
 * 币种币种
 */

namespace app\admin\service;

use app\admin\model\Algorithm;
use think\Service;
use app\admin\model\ProductCurrency as CurrencyModel;

class Currency extends BaseService
{

    /**
     * 获取币种列表
     * @param $param
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($param = [], $page = 1, $limit = 10)
    {
        $where = [['is_del', '=', 0]];
        $arrData = ['code' => 0, 'message' => 'success'];
        if ($param['name']) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }
        if ($param['name_short']) {
            $where[] = ['name_short', 'like', '%' . $param['name_short'] . '%'];
        }

        $oCurrencyModel = CurrencyModel::where($where);
        $total = $oCurrencyModel->count();
        $result = $oCurrencyModel->with(['get_creator_name', 'get_update_name'])->page($page, $limit)->order('if_show desc , sort asc')->select();


        $algorithmModel = new Algorithm();
        // 直接获取需要的字段，使用 array_column 一次性处理
        $algorithmArray = array_column(
            $algorithmModel->getFieldEnum('algorithm')['algorithm'],
            'label',
            'value'
        );

        $showArray = array_column(
            $algorithmModel->getFieldEnum('if_show')['if_show'],
            'label',
            'value'
        );
        // 使用 collection 的 map 方法替代 foreach
        $result = $result->map(function ($item) use ($algorithmArray,$showArray) {
            if (is_numeric($item->algorithm)) {
                $item['algorithm_name'] = $algorithmArray[$item->algorithm] ?? '';
            }
            if (is_numeric($item->if_show)) {
                $item['show_status'] = $showArray[$item->if_show] ?? '';
            }
            return $item;
        });

        $arrData['data'] = ['list' => $result->toArray(), 'total' => $total];
        return $arrData;
    }

    /**
     * 删除单条或多条币种数据
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($param)
    {
        $where = [['is_del', '=', '0'], ['id', 'in', $param['ids']]];
        $oCurrencyModel = CurrencyModel::where($where);
        $currency = $oCurrencyModel->find();
        if (!$currency) {
            return ['code' => 1, 'message' => '获取币种信息失败！'];
        }
        $result = $oCurrencyModel->update(['is_del' => time()]);
        if ($result) {
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            $this->logger->logOperation($param['ids'], 'Currency', '删除', '删除币种');
            return ['code' => 0, 'message' => '删除币种成功！'];
        } else {
            return ['code' => 1, 'message' => '删除币种失败！'];
        }
    }

    /**
     * 添加修改币种
     * @param $param
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save($param)
    {
        $checkCurrencyModel = CurrencyModel::where([['name', '=', $param['name']], ['is_del', '=', 0]]);
        if ($param['id']) {
            $checkCurrencyModel->where('id', '<>', $param['id']);
        }
        if ($checkCurrencyModel->find()) {
            return ['code' => 1, 'message' => '币种名称重复！'];
        }

        if ($param['id']) {
            $oCurrencyModel = CurrencyModel::find($param['id']);
            $oCurrencyModel->updater = $param['operator_id'];
            $oCurrencyModel->update_time = date('Y-m-d H:i:s', time());
        } else {
            $oCurrencyModel = new CurrencyModel();
            $oCurrencyModel->creator = $param['operator_id'];
            $oCurrencyModel->create_time = date('Y-m-d H:i:s', time());
            $oCurrencyModel->is_del = 0;
        }

        $oCurrencyModel->name = $param['name'];
        $oCurrencyModel->algorithm = $param['algorithm'];
        $oCurrencyModel->image = $param['image'];
        $oCurrencyModel->name_short = $param['name_short'];
        $oCurrencyModel->description = $param['description'];
        $oCurrencyModel->if_show = $param['if_show'];
        $oCurrencyModel->sort = $param['sort'];

        if ($oCurrencyModel->save()) {
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            $this->logger->logOperation($oCurrencyModel->id, 'Currency', '添加/修改', '添加/修改币种');
            return ['code' => 0, 'message' => '保存币种成功！'];
        }
    }

    /**
     * 获取单个币种信息
     * @param int $id 币种ID
     * @return array
     */
    public function getInfo($param)
    {
        $where = [['is_del', '=', '0'], ['id', '=', $param['id']]];
        $oCurrencyModel = CurrencyModel::where($where)->with(['get_creator_name', 'get_update_name'])->find();
        if (!$oCurrencyModel) {
            return ['code' => 1, 'message' => '获取币种信息失败！'];
        }
        $algorithmModel = new Algorithm();
        $algorithmArray = array_column(
            $algorithmModel->getFieldEnum('algorithm')['algorithm'],
            'label',
            'value'
        );
        if (is_numeric($oCurrencyModel->algorithm)) {
            $oCurrencyModel->algorithm_name = $algorithmArray[$oCurrencyModel->algorithm] ?? '';
            $oCurrencyModel->algorithm = intval($oCurrencyModel->algorithm);
        }

        return ['code' => 0, 'message' => 'success', 'data' => $oCurrencyModel];
    }

    public function getSelect()
    {
        $where = [['is_del', '=', 0]];
        $arrData = ['code' => 0, 'message' => 'success'];

        $oCategoryModel = CurrencyModel::where($where);
        $total = $oCategoryModel->count();
        $result = $oCategoryModel->field('id AS value,name_short as label,name')->select();
        $arrData['data'] = ['list' => $result->toArray(), 'total' => $total];
        return $arrData;
    }


    /**
     *   获取枚举
     */
    public function getEnum($param)
    {
        $Algorithm = new Algorithm();
        $result = $Algorithm->getFieldEnum($param['field']);
        $arrData = ['code' => 0, 'message' => 'success', 'data' => $result];
        return $arrData;
    }
}
